// pages/weiixuxiadan/weiixuxiadan.js
var common = require('../../js/common.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var  that =this;

    if (wx.getStorageSync("address")){
      that.setData({
        address: wx.getStorageSync("address"),
        
      })
    }else{
      common.request(app.globalData.localUrl, 'defaultAddress', {
        user_id: wx.getStorageSync("userInfo").id
      },
        function (res) {
          console.log('默认地址详情', res)
          if (res.data.code == 1) {
            that.setData({
              address: res.data.data
            })
            // that.getdatalist();
          }
        }, 'rtype= post');
    }

    if (wx.getStorageSync("shebei")) {
      that.setData({
        shebei: wx.getStorageSync("shebei"),
      })
    }

    if (wx.getStorageSync("tempFilePaths")) {
      that.setData({
        tempFilePaths: wx.getStorageSync("tempFilePaths"),
      })
    }
    
  },
  shanchu:function(e){
    var dataset = e.target.dataset;
    var Index = dataset.index;
    //通过index识别要删除第几条数据，第二个数据为要删除的项目数量，通常为1
    this.data.shebei.splice(Index, 1);
    wx.setStorageSync('shebei', this.data.shebei)
    //渲染数据
    this.setData({
      shebei: this.data.shebei
    });
  
  },

  //减去商品数量
  jianfa: function (e) {
     var dataset = e.target.dataset;
    var Index = dataset.index;
    var num = this.data.shebei[Index].shu;
    var shebei = this.data.shebei;
    var num2 = Number(num) - 1;
    if (num2 < 1) {
      this.data.shebei.splice(Index, 1);
      wx.setStorageSync('shebei', this.data.shebei)
      //渲染数据
      this.setData({
        shebei: this.data.shebei
      });
    }
    var shebeilist2 =[];
    for (let i = 0; i < shebei.length; ++i) {
      shebeilist2[i] = shebei[i];
      if (i == Index) {
        shebeilist2[i].shu = Number(shebei[i].shu) -1;
      }
    }
    wx.setStorageSync('shebei', shebeilist2)
    this.setData({
      shebei: shebeilist2
    })

  },

  //加去商品数量
  jiafa: function (e) {
    var dataset = e.target.dataset;
    var Index = dataset.index;
    var num = this.data.shebei[Index].shu;
    var shebei = this.data.shebei;
    var num2 = Number(num) + 1;
 
    var shebeilist2 = [];
    for (let i = 0; i < shebei.length; ++i) {
      shebeilist2[i] = shebei[i];
      if (i == Index) {
        shebeilist2[i].shu = shebei[i].shu + 1;
      }
    }
    wx.setStorageSync('shebei', shebeilist2)
    this.setData({
      shebei: shebeilist2
    })

  },


  deimag: function (e) {
    var ids = e.currentTarget.dataset.id;
    var tempFilePathss = this.data.tempFilePaths;
    tempFilePathss.splice(ids, 1);
    this.setData({
      tempFilePaths: tempFilePathss
    });
    wx.setStorageSync('tempFilePaths', tempFilePathss);
  },

  /**
* 上传图片
*/
  uploadimg: function () {
    var that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.setData({
          tempFilePath: res.tempFilePaths
        });
        wx.uploadFile({
          url: app.globalData.localUrl + 'updateimg', //仅为示例，非真实的接口地址//接口连接
          filePath: that.data.tempFilePath['0'],
          name: 'img',
          header: {
            "Content-Type": "multipart/form-data"
          },
          formData: {
            'oid': that.data.oid
          },
          success: function (res) {
            
            var tempFilePaths = wx.getStorageSync("tempFilePaths");
            var imgUrl = JSON.parse(res.data).data;
            if (tempFilePaths==''){
              tempFilePaths = [imgUrl];
            }else{
              tempFilePaths.push(imgUrl);
            }
            console.log(imgUrl)
            
            that.setData({
              tempFilePath: tempFilePaths
            });
         wx.setStorageSync('tempFilePaths', tempFilePaths)

         that.onLoad();
            // that.data.tempFilePaths.push(imgUrl);
            // tempFilePaths.push(imgUrl);
          
            // that.setData({
            //   uploadimg: '上传成功'
            // })
            //do something
          }
        })
      }
    })
  },


  formSubmit: function (e) {
    var that = this;

    wx.showLoading({
      title: '保存中',
      mask: true
    })
    var shebei = that.data.shebei;
    var address_id = that.data.address.id;
    var tools = '';
    for (let i = 0; i < shebei.length; ++i) {
      if (i == 0) {
        tools += shebei[i].id + ',' + shebei[i].shu;
      } else {
        tools += ";" + shebei[i].id + ',' + shebei[i].shu;
      }

      // tool[i] = {
      //   tool_id: shebei[i].id,
      //   num: shebei[i].shu
      // };
     
    }
    console.log('address_id=' + address_id)
    console.log('tool=' + tools)
    console.log('remark=' + e.detail.value.remark)
    console.log('user_id=' + wx.getStorageSync('userInfo').id)


    if (address_id === '') {
      wx.showToast({
        title: '地址不能为空',
        icon: 'none',
        duration: 1500
      });
      return false;
    } 
   
    if (e.detail.value.name == '') {
      wx.showToast({
        title: '名字不为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (!tools) {
      wx.showToast({
        title: '设备还没选',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    var tempFilePaths = that.data.tempFilePaths;
    if (tempFilePaths){
      tempFilePaths = tempFilePaths.join(",");
    }
      
   
    // if (tempFilePaths == '') {
    //   wx.showToast({
    //     //title: '图片不能为空',
    //     title: '请上传图片',
    //     icon: 'none'
    //   })
    //   that.setData({
    //     flag: true
    //   })
    //   return;
    // }
    common.request(app.globalData.localUrl, 'orderAdd', {
      user_id: wx.getStorageSync('userInfo').id,
      address_id: address_id,
      tool: tools,
      imgs: tempFilePaths,
      remark: e.detail.value.remark
    },
      function (res) {
        console.log('新增订单', res)
        if (res.data.code == 1) {
          wx.showToast({
            title: '新增成功',
            icon: 'success',
            mask: true
          })
          //发送通知给z自己以及接收人openid
          var data2 = {
            "touser": 'osf6K5XD92DnDkkdaB4TgScnSK6E',
            "mp_template_msg": {
              "appid": 'wx583558587c71ba26',
              "template_id": "FKI292URmD-WEYGdHffSiSsRo_xmZ7VpGacS3iQ4rrY",
              "url": "http://hpty.10gzs.com",
              "miniprogram": {
                "appid": "wxe6273d73fcb391a5",
                "pagepath": "pages/weiixuxiadan/weiixuxiadan"
              },
              "data": {
                "first": {
                  "value": "您好，有新订单需要受理",
                  "color": "#173177"
                },
                "keyword1": {
                  "value": 'NL45645645646',
                  "color": "#173177"
                },
                "keyword2": {
                  "value": '待受理订单',
                  "color": "#173177"
                },
                "keyword3": {
                  "value": '2018-02-13',
                  "color": "#173177"
                },
                "keyword4": {
                  "value": '张建 15827024197',
                  "color": "#173177"
                },
                 "remark": {
                   "value": '有订单需要受理，请及时受理',
                  "color": "#173177"
                }
              }
            }

          };
          that.send_message(data2, res.data.token);
          wx.removeStorageSync('tempFilePaths');//清空图片缓存
          wx.removeStorageSync('shebei');//清空内容缓存
          setTimeout(function () {
           wx.navigateTo({
              url: '/pages/smorder/smorder'
            })

          }, 1500);

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1500
          })
        }
      }
    );

  },
  send_message:function(data, access_token) {
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_token,
      data: data,
      method: 'POST',
      success: function (res) {
      console.log(res);
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})